package com.bytz.modules.cms.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bytz.common.exception.BytzBootException;
import com.bytz.common.system.base.service.impl.AbstractCrudService;
import com.bytz.common.system.query.QueryGenerator;
import com.bytz.common.util.PageUtils;
import com.bytz.modules.cms.common.util.ExcelUtil;
import com.bytz.modules.cms.order.constant.OfflinePayConstants;
import com.bytz.modules.cms.order.entity.OrderOfflinePay;
import com.bytz.modules.cms.order.mapper.OrderOfflinePayMapper;
import com.bytz.modules.cms.order.model.OrderBillExcel;
import com.bytz.modules.cms.order.model.OrderOfflinePayExcelVo;
import com.bytz.modules.cms.order.model.OrderOfflinePayModel;
import com.bytz.modules.cms.order.service.IAdminOrderOfflinePayService;
import com.bytz.modules.cms.order.service.constants.BillConstants;
import com.bytz.modules.cms.reseller.entity.Reseller;
import com.bytz.modules.cms.reseller.service.IResellerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author fengwenhao
 */
@Service
public class AdminOrderOfflinePayServiceImpl extends AbstractCrudService<OrderOfflinePayMapper, OrderOfflinePay, OrderOfflinePay> implements IAdminOrderOfflinePayService {

    @Autowired
    private IResellerService resellerService;

    @Override
    protected OrderOfflinePay insertSaveObject(OrderOfflinePay saveRo) {

        saveRo.setRemainAmount(saveRo.getRemitAmount());
        saveRo.setStatus(OfflinePayConstants.OfflinePayStatus.AVAILABLE);
        saveRo.setType(OfflinePayConstants.OfflinePayType.NORMAL);

        save(saveRo);
        return saveRo;
    }

    @Override
    protected OrderOfflinePay updateSaveObject(OrderOfflinePay saveRo) {
        updateById(saveRo);
        return saveRo;
    }

    @Override
    protected OrderOfflinePay saveOthers(OrderOfflinePay saveRo) {
        return null;
    }

    @Override
    protected boolean deleteEntity(OrderOfflinePay entity) {
        return removeById(entity.getId());
    }

    @Override
    protected void deleteOthers(OrderOfflinePay entity) {

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importExcel(List<OrderOfflinePay> offlinePays) {

        if (CollectionUtil.isEmpty(offlinePays)) {
            return;
        }

        List<String> resellerNames = offlinePays.stream().map(OrderOfflinePay::getResellerName).collect(Collectors.toList());
        Map<String, Reseller> resellerMap = resellerService.getByNames(resellerNames).stream().collect(Collectors.toMap(Reseller::getResellerName, r -> r));

        offlinePays.forEach(offlinePay -> {
            offlinePay.setStatus(OfflinePayConstants.OfflinePayStatus.AVAILABLE);
            offlinePay.setType(OfflinePayConstants.OfflinePayType.NORMAL);
            offlinePay.setRemainAmount(offlinePay.getRemitAmount());

            Reseller reseller = resellerMap.get(offlinePay.getResellerName());

            if (reseller == null) {

                throw new BytzBootException("没有找到" + offlinePay.getResellerName() + "对应的经销商");
            }

            offlinePay.setResellerId(reseller.getId());
        });

        saveBatch(offlinePays);
    }

    @Override
    public IPage<OrderOfflinePayModel> queryPage(Page<OrderOfflinePay> reqPage, OrderOfflinePay offlinePay, Map<String, String[]> parameterMap) {
        QueryWrapper<OrderOfflinePay> wrapper = QueryGenerator.initQueryWrapper(offlinePay, parameterMap);
        Page<OrderOfflinePay> page = page(reqPage, wrapper);
        return PageUtils.convertPage(page, OrderOfflinePayModel.class, (out, in) -> {
            out.setCanEdit(in.getEffectTime().compareTo(LocalDateTime.now()) > 0);
        });
    }

    @Override
    public void exportExcel(OrderOfflinePay offlinePay, Map<String, String[]> parameterMap, HttpServletResponse response) throws IOException {
        QueryWrapper<OrderOfflinePay> wrapper = QueryGenerator.initQueryWrapper(offlinePay, parameterMap);
        List<OrderOfflinePay> list = list(wrapper);
        List<OrderOfflinePayExcelVo> orderOfflinePayExcelVos = BeanUtil.copyToList(list, OrderOfflinePayExcelVo.class);
        AtomicInteger atomicInteger = new AtomicInteger(1);
        orderOfflinePayExcelVos.forEach(e -> e.setSequence(atomicInteger.getAndIncrement()));
        ExcelUtil.export(
                String.format(BillConstants.OrderOfflinePay.ATTACH_NAME, LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME.withLocale(Locale.CHINA))),
                OrderOfflinePayExcelVo.class,
                response,
                orderOfflinePayExcelVos
        );
    }
}